<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="责任部门" prop="videoOrigin">
        <el-input
          v-model="queryParams.videoOrigin"
          placeholder="请输入责任部门"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="责任编辑" prop="author">
        <el-input
          v-model="queryParams.author"
          placeholder="请输入责任编辑"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="视频类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择"
                   clearable
        >
          <el-option
            v-for="dict in dict.type.video_kind"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['partyclass:partyclass:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['partyclass:partyclass:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['partyclass:partyclass:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['partyclass:partyclass:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="partyclassList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!-- <el-table-column label="id" align="center" width="55" prop="id"/> -->
      <el-table-column label="名称" align="center" prop="name"/>
      <!-- 视频类型 -->
      <el-table-column label="视频类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.video_kind" :value="scope.row.type"></dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="视频" align="center" prop="file">
        <template slot-scope="scope">
          <video :src="scope.row.file" :width="150" :height="100" @click="playVideo(scope.row.file)"
                 style="cursor: pointer;"/>
        </template>
      </el-table-column>
      <el-table-column label="封面" align="center" prop="coverImg">
        <template slot-scope="scope">
          <image-preview :src="scope.row.coverImg" :width="150" :height="100" v-if="scope.row.coverImg"/>
          <span v-else>无封面</span>
        </template>
      </el-table-column>
      <el-table-column label="责任编辑" align="center" prop="author">
        <template slot-scope="scope">
          <span>{{ !scope.row.author || scope.row.author === 'null' ? '-' : scope.row.author }}</span>
        </template>
      </el-table-column>
      <el-table-column label="责任部门" align="center" prop="videoOrigin">
        <template slot-scope="scope">
          <span>{{ !scope.row.videoOrigin || scope.row.videoOrigin === 'null' ? '-' : scope.row.videoOrigin }}</span>
        </template>
      </el-table-column>
      <el-table-column label="日期" align="center" prop="pubdate"/>
      <el-table-column label="排序" align="center" prop="sortOrder" sortable/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-top"
            @click="moveToTop(scope.row)"
            v-hasPermi="['partyclass:partyclass:edit']"
          >置顶
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-arrow-up"
            @click="moveUp(scope.row)"
            v-hasPermi="['partyclass:partyclass:edit']"
          >上移
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-arrow-down"
            @click="moveDown(scope.row)"
            v-hasPermi="['partyclass:partyclass:edit']"
          >下移
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['partyclass:partyclass:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-finished"
            @click="handlePublish(scope.row)"
            v-hasPermi="['partyclass:partyclass:publish']"
          >{{ scope.row.publish ? '取消发布' : '发布' }}
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['partyclass:partyclass:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改partyclass对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称"/>
        </el-form-item>
        <el-form-item label="视频类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择">
            <el-option
              v-for="dict in dict.type.video_kind"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="视频路径" prop="file">
          <input type="file" @change="handleFileUpload" ref="videoInput">
          <div v-if="originalVideoPath">当前视频路径：{{ originalVideoPath }}</div>
          <div v-if="isFileSelected">已选文件：{{ form.file.name }}</div>
        </el-form-item>
        <el-form-item label="封面路径" prop="coverImg">
          <input type="file" @change="handleImgFileUpload" ref="coverImgInput">
          <div v-if="originalCoverImgPath">当前封面路径：{{ originalCoverImgPath }}</div>
          <div v-if="isImgFileSelected">已选文件：{{ form.coverImg.name }}</div>
        </el-form-item>
        <el-form-item label="责任编辑" prop="author">
          <el-input v-model="form.author" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="责任部门" prop="videoOrigin">
          <el-input v-model="form.videoOrigin" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="日期" prop="pubdate">
          <el-date-picker clearable v-model="form.pubdate" type="date" value-format="yyyy-MM-dd"
                          placeholder="选择日期"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 进度条模拟文件上传 -->
    <!-- 进度条弹窗 -->
    <el-dialog
      :visible.sync="progressVisible"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="400px"
      center
    >
      <div style="text-align: center; padding: 20px;">
        <p style="margin-bottom: 15px; font-size: 16px;">{{ uploadStatusText }}</p>
        <el-progress
          :percentage="progressPercent"
          :format="() => `${progressPercent}%`"
          status="success"
          style="margin: 0 auto 10px;"
        />
        <p v-if="progressPercent < 100" style="color: #999; font-size: 13px;">
          数据提交中，请勿关闭窗口
        </p>
        <p v-else style="color: #67C23A; font-size: 13px;">
          提交完成
        </p>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPartyclass,
  getPartyclass,
  delPartyclass,
  addPartyclass,
  updatePartyclass,
  updatePartyclassSortOrder,
  moveUp,
  moveDown,
  moveToTop,
  publishPartyVideo,
} from "@/api/partyclass/partyclass";
import {computed} from "vue";

export default {
  name: "Partyclass",
  dicts: ['video_kind'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // partyclass表格数据
      partyclassList: [],
      // 新增：进度条相关
      progressVisible: false,
      progressPercent: 0,
      showProgressBar: false,
      uploadStatusText: '正在提交数据，请稍候...', // 上传状态文本
      originalVideoPath: '',   // 原始视频路径
      originalCoverImgPath: '',// 原始封面路径
      originalName: '',         // 原名称
      originalFileName: '',     // 原文件名
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        videoOrigin: null,
        author: null,
        type: null,
      },
      // 表单参数
      form: {
        id: null,
        name: null,
        file: null,
        coverImg: null,
        pubdate: null,
        author: null,
        videoOrigin: null,
        type: null
      },
      // 表单校验
      rules: {},
      isEdit: false,
    };
  },
  created() {
    this.getList();
    // 监听数据恢复事件
    this.$bus.$on('videoDataRecovered', () => {
      console.log('视频页面收到恢复事件，开始刷新列表');
      this.getList();
    });
  },
  beforeDestroy() {
    // 移除事件监听
    this.$bus.$off('videoDataRecovered');
  },

  computed: {
    isFileSelected() {
      return this.form.file instanceof File;
    },
    isImgFileSelected() {
      return this.form.coverImg instanceof File;
    }
  },

  methods: {
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    handleFileUpload(event) {
      const file = event.target.files[0];
      console.log('选择视频文件:', file);
      this.form.file = file;
      console.log('form.file 已设置:', this.form.file);
    },
    handleImgFileUpload(event) {
      const file = event.target.files[0];
      console.log('选择封面文件:', file);
      this.form.coverImg = file;
      console.log('form.coverImg 已设置:', this.form.coverImg);
    },
    /** 查询partyclass列表 */
    getList() {
      this.loading = true;
      listPartyclass(this.queryParams).then(response => {
        this.partyclassList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.$refs.videoInput.value = '';
      if (this.$refs.coverImgInput) {
        this.$refs.coverImgInput.value = '';
      }
      this.progressVisible = false; // 关闭进度条弹窗
      this.uploadStatusText = '正在提交数据，请稍候...'; // 重置上传状态文本
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        file: null,
        coverImg: null,
        pubdate: null,
        author: null,
        videoOrigin: null,
        type: null
      };
      this.resetForm("form");
      this.uploadStatusText = '正在提交数据，请稍候...'; // 重置上传状态文本
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.isEdit = false;
      this.originalVideoPath = '';   // 原始视频路径
      this.originalCoverImgPath = ''; // 原始封面路径
      // 自动设置办结日期为当前时间
      const now = new Date();
      this.form.pubdate = this.formatDate(now);
      this.open = true;
      this.title = "添加视频";
      // 手动清空文件输入框（DOM 层面）
      if (this.$refs.videoInput) {
        this.$refs.videoInput.value = '';
      }
      if (this.$refs.coverImgInput) {
        this.$refs.coverImgInput.value = '';
      }
    },

    async handlePublish(row) {
      try {
        const id = row?.id || (Array.isArray(this.ids) && this.ids[0]);
        if (!id) {
          this.$modal.msgError("请选择要发布的数据");
          return;
        }

        const res = await publishPartyVideo(id);
        console.log('发布响应:', res); // 调试信息

        if (res.code === 200) {
          this.getList();
          this.$modal.msgSuccess(res.msg || "操作成功");
        } else {
          this.$modal.msgError(res.msg || "操作失败");
        }
      } catch (e) {
        console.error('发布失败:', e);
        this.$modal.msgError("发布失败: " + (e.message || "未知错误"));
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.isEdit = true;

      const id = row?.id || (Array.isArray(this.ids) && this.ids[0]);
      if (!id) {
        this.$modal.msgError("请选择要修改的数据");
        return;
      }

      getPartyclass(id).then(response => {
        const data = response.data;
        console.log('字典数据:', this.dict.type.video_kind);
        console.log('当前数据:', data);
        this.originalVideoPath = data.file || '';
        this.originalCoverImgPath = data.coverImg || '';
        this.originalName = data.name;
        this.originalFileName = data.file || '';
        this.form = {...data};
        // 确保视频类型值正确设置，处理数据类型匹配问题
        if (data.type !== undefined && data.type !== null) {
          // 查找字典中是否存在该值，确保类型匹配
          const dictOption = this.dict.type.video_kind.find(option =>
            option.value.toString() === data.type.toString());
          if (dictOption) {
            this.form.type = dictOption.value;
          } else {
            this.form.type = data.type;
          }
        }
        // 自动设置办结日期为当前时间
        if (!this.form.pubdate) {
          const now = new Date();
          this.form.pubdate = this.formatDate(now);
        }
        this.open = true;
        this.title = "修改视频";
      });
    },
    /** 提交按钮 */
    async submitForm() {
      this.$refs["form"].validate(async valid => {
        if (!valid) return;

        try {
          // 校验：如果只有视频、没有封面 → 阻止提交（可选）
          const hasNewVideo = this.form.file instanceof File;
          const hasNewCover = this.form.coverImg instanceof File;

          console.log('=== 表单提交前检查 ===');
          console.log('form.file:', this.form.file);
          console.log('form.coverImg:', this.form.coverImg);
          console.log('hasNewVideo:', hasNewVideo);
          console.log('hasNewCover:', hasNewCover);

          const formData = new FormData();
          formData.append("name", this.form.name);
          formData.append("pubdate", this.form.pubdate);
          formData.append("author", this.form.author);
          formData.append("video_origin", this.form.videoOrigin);
          formData.append("type", this.form.type);

          if (this.form.file instanceof File) {
            formData.append("file", this.form.file);
            console.log('已添加视频文件到FormData');
          }

          if (this.form.coverImg instanceof File) {
            formData.append("cover_img", this.form.coverImg);
            console.log('已添加封面文件到FormData');
          }

          let id;
          if (this.isEdit) {
            id = Number(this.form.id);
            if (!id || isNaN(id)) {
              this.$modal.msgError("请选择有效的数据进行修改");
              return;
            }
          }

          // 判断是否需要进入进度条流程（只要有文件上传就走进度条）
          const mustUseProgressBar = hasNewVideo || hasNewCover;

          // ====== 如果不需要进度条（即只改文本）→ 快速提交 ======
          if (!mustUseProgressBar) {
            const apiFn = this.isEdit ? updatePartyclass : addPartyclass;

            this.open = false;

            // 对于新增操作，不需要传递id参数
            const apiCall = this.isEdit ? apiFn(id, formData) : apiFn(formData);

            apiCall
              .then(() => {
                this.getList();
                this.$modal.msgSuccess(this.isEdit ? "修改成功" : "新增成功");
              })
              .catch(err => {
                this.$modal.msgError("提交失败：" + err.message);
                this.open = false;
              });

            return;
          }

          // ====== 有文件上传 → 进入进度条 + 轮询检测 ======
          // 关闭弹窗，显示进度条
          this.open = false;
          this.progressVisible = true;
          this.progressPercent = 0;

          // 设置上传状态文本
          this.uploadStatusText = hasNewVideo ?
            (hasNewCover ? '正在上传视频和封面文件，请稍候...' : '正在上传视频文件，请稍候...') :
            '正在上传封面文件，请稍候...';

          const apiFn = this.isEdit ? updatePartyclass : addPartyclass;

          // 对于新增操作，不需要传递id参数
          const apiCall = this.isEdit ? apiFn(id, formData) : apiFn(formData);

          apiCall.then(res => {
            console.log('提交完成', res);

            // 添加调试日志
            console.log('当前表单数据:', this.form);
            console.log('是否有新视频:', hasNewVideo);
            console.log('是否有新封面:', hasNewCover);
            console.log('是否为编辑模式:', this.isEdit);

            // 获取新增记录的ID（如果是新增模式）
            let recordId = this.isEdit ? this.form.id : null;
            // 处理不同的返回格式
            if (!this.isEdit) {
              if (res.data && res.data.data && res.data.data.id) {
                // 格式: { code: 200, msg: "已提交上传任务，请等待完成", data: {id: 1, ...} }
                recordId = res.data.data.id;
              } else if (res.data && res.data.id) {
                // 格式: { code: 200, msg: "已提交上传任务，请等待完成", data: Partyclass对象 }
                recordId = res.data.id;
              }
              console.log('新增记录ID:', recordId);
            }

            let interval = null;

            // 启动进度条动画
            const startProgressBar = () => {
              this.progressPercent = 0;
              console.log('启动进度条动画');

              interval = setInterval(() => {
                if (this.progressPercent < 90) {
                  this.progressPercent += 5;
                  if (this.progressPercent > 90) this.progressPercent = 90;
                  console.log('进度条阶段1:', this.progressPercent);
                } else if (this.progressPercent < 99) {
                  this.progressPercent += 1; // 每次加 1%
                  console.log('进度条阶段2:', this.progressPercent);
                } else {
                  // 到达 99%，开始波动动画
                  const fluctuation = Math.random() > 0.5 ? 1 : -1;
                  this.progressPercent = Math.min(99, Math.max(95, this.progressPercent + fluctuation));
                  console.log('进度条波动阶段:', this.progressPercent);
                }
              }, this.progressPercent < 90 ? 500 : 1000); // 不同阶段不同间隔
            };

            startProgressBar();

            // 新增模式：使用ID轮询判断上传完成
            if (!this.isEdit && recordId) {
              const hasNewVideo = this.form.file instanceof File;
              const hasNewCover = this.form.coverImg instanceof File;

              let attempt = 0;
              const maxAttempts = 30;

              const polling = setInterval(() => {
                attempt++;
                getPartyclass(recordId).then(res => {
                  if (!res || !res.data) {
                    console.warn("获取数据失败");
                    return;
                  }

                  const data = res.data;

                  // 判断字段是否非空
                  const videoNotEmpty = data.file && data.file.trim() !== '';
                  const coverNotEmpty = data.coverImg && data.coverImg.trim() !== '';

                  let uploadCompleted = false;

                  // 根据上传类型判断是否完成
                  if (hasNewVideo && hasNewCover) {
                    uploadCompleted = videoNotEmpty && coverNotEmpty;
                  } else if (hasNewVideo) {
                    uploadCompleted = videoNotEmpty;
                  } else if (hasNewCover) {
                    uploadCompleted = coverNotEmpty;
                  } else {
                    // 没有文件上传
                    uploadCompleted = true;
                  }

                  if (uploadCompleted) {
                    clearInterval(interval);
                    clearInterval(polling);
                    this.progressPercent = 100;

                    setTimeout(() => {
                      this.progressVisible = false;
                      this.getList();
                      this.$modal.msgSuccess("新增成功");
                    }, 300);
                  }
                }).catch(err => {
                  console.error('查询失败:', err);
                });

                // 超时控制
                if (attempt > maxAttempts) {
                  clearInterval(interval);
                  clearInterval(polling);
                  this.progressPercent = 100;

                  setTimeout(() => {
                    this.progressVisible = false;
                    this.getList();
                    this.$modal.msgWarning("超时，请稍后刷新页面确认状态");
                  }, 300);
                }
              }, 2000);
            }

            // 修改模式：轮询判断视频和封面是否变化
            if (this.isEdit) {
              const id = this.form.id;
              const originalVideoPath = this.originalVideoPath;
              const originalCoverPath = this.originalCoverImgPath;

              let attempt = 0;
              const maxAttempts = 30;
              const polling = setInterval(() => {
                attempt++;
                getPartyclass(id).then(res => {
                  console.log('轮询获取数据:', res);
                  if (!res || !res.data) {
                    console.warn("获取数据失败，接口返回为空");
                    this.$modal.msgError("获取数据失败，请刷新页面重试");
                    clearInterval(interval);
                    clearInterval(polling);
                    this.progressPercent = 100;

                    setTimeout(() => {
                      this.progressVisible = false;
                      this.getList();
                    }, 300);
                    return;
                  }

                  const data = res.data;
                  const currentVideoPath = data.file || '';
                  const currentCoverPath = data.coverImg || '';

                  const hasNewVideo = this.form.file instanceof File;
                  const hasNewCover = this.form.coverImg instanceof File;

                  // 判断当前字段是否已更新
                  const videoUpdated = currentVideoPath !== originalVideoPath;
                  const coverUpdated = currentCoverPath !== originalCoverPath;

                  // 添加调试日志
                  console.log('原始视频路径:', originalVideoPath);
                  console.log('当前视频路径:', currentVideoPath);
                  console.log('视频是否更新:', videoUpdated);
                  console.log('原始封面路径:', originalCoverPath);
                  console.log('当前封面路径:', currentCoverPath);
                  console.log('封面是否更新:', coverUpdated);

                  // 根据上传类型决定完成条件
                  // 修复：同时上传视频和封面时的处理逻辑
                  let uploadCompleted = false;
                  if (hasNewVideo && hasNewCover) {
                    // 同时上传视频和封面，需要两个都更新
                    // 但考虑到视频上传时间更长，如果视频更新了就认为基本完成
                    uploadCompleted = videoUpdated;
                    // 如果封面也更新了，那就更好了
                    if (coverUpdated) {
                      uploadCompleted = videoUpdated && coverUpdated;
                    }
                  } else if (hasNewVideo && !hasNewCover) {
                    // 只上传视频
                    uploadCompleted = videoUpdated;
                  } else if (!hasNewVideo && hasNewCover) {
                    // 只上传封面
                    uploadCompleted = coverUpdated;
                  }

                  // 添加调试信息
                  console.log('上传完成判断结果:', uploadCompleted);
                  console.log('判断条件: hasNewVideo=' + hasNewVideo + ', hasNewCover=' + hasNewCover +
                    ', videoUpdated=' + videoUpdated + ', coverUpdated=' + coverUpdated);

                  if (uploadCompleted) {
                    console.log('上传完成，关闭进度条');
                    clearInterval(interval);
                    clearInterval(polling);
                    this.progressPercent = 100;

                    setTimeout(() => {
                      this.progressVisible = false;
                      this.getList();
                      this.$modal.msgSuccess("修改成功");
                    }, 300);
                  }
                }).catch(err => {
                  console.error('查询失败:', err);
                  this.$modal.msgError("查询失败：" + err.message);
                  clearInterval(interval);
                  clearInterval(polling);
                  this.progressPercent = 100;

                  setTimeout(() => {
                    this.progressVisible = false;
                    this.getList();
                  }, 300);
                });

                // 超时控制
                if (attempt > maxAttempts) {
                  clearInterval(interval);
                  clearInterval(polling);
                  this.progressPercent = 100;

                  setTimeout(() => {
                    this.progressVisible = false;
                    this.getList();
                    this.$modal.msgWarning("超时,后台仍在上传处理中,请稍后刷新");
                  }, 300);
                }
              }, 2000);
            }

          }).catch(err => {
            console.error('提交失败:', err);
            this.$modal.msgError("提交失败：" + (err.message || "网络错误"));
            // 确保进度条关闭
            this.progressVisible = false;
            // 确保主对话框关闭
            this.open = false;
          });
        } catch (error) {
          console.error('操作失败:', error);
          // 发生错误时关闭加载提示
          if (this.$loading) {
            // 关闭所有加载实例
            const loadingInstances = document.querySelectorAll('.el-loading-mask');
            if (loadingInstances.length > 0) {
              this.$loading().close();
            }
          }
          this.$message.error(`操作失败: ${error.message}`);
          this.open = false;
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除partyclass编号为"' + ids + '"的数据项？').then(function () {
        return delPartyclass(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
        // 触发事件通知回收站页面刷新
        console.log('触发删除事件: videoDataDeleted');
        this.$bus.$emit('videoDataDeleted');
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('partyclass/partyclass/export', {
        ...this.queryParams
      }, `partyclass_${new Date().getTime()}.xlsx`)
    },
    /** 播放视频 */
    playVideo(videoUrl) {
      // 创建一个模态框来播放视频
      const videoHtml = `<video id="videoPlayer" src="${videoUrl}" controls style="max-width: 100%; max-height: 80vh; width: 100%;"></video>`;

      this.$alert(videoHtml, '视频播放', {
        dangerouslyUseHTMLString: true,
        showCancelButton: false,
        showConfirmButton: true,
        confirmButtonText: '关闭',
        closeOnClickModal: true,
        customClass: 'video-modal',
        callback: action => {
          // 关闭模态框时停止视频播放
          const videoPlayer = document.getElementById('videoPlayer');
          if (videoPlayer) {
            videoPlayer.pause();
            videoPlayer.currentTime = 0;
          }
        },
        beforeClose: (action, instance, done) => {
          // 无论哪种方式关闭模态框都停止视频播放
          const videoPlayer = document.getElementById('videoPlayer');
          if (videoPlayer) {
            videoPlayer.pause();
            videoPlayer.currentTime = 0;
          }
          done();
        }
      });
    },

    /** 上移 */
    moveUp(row) {
      moveUp(row.id).then(response => {
        this.$modal.msgSuccess("上移成功");
        this.getList(); // 重新加载数据
      }).catch(error => {
        this.$modal.msgError("操作失败: " + error.message);
      });
    },

    /** 下移 */
    moveDown(row) {
      moveDown(row.id).then(response => {
        this.$modal.msgSuccess("下移成功");
        this.getList(); // 重新加载数据
      }).catch(error => {
        this.$modal.msgError("操作失败: " + error.message);
      });
    },

    /** 移至顶部 */
    moveToTop(row) {
      moveToTop(row.id).then(response => {
        this.$modal.msgSuccess("已移至顶部");
        this.getList(); // 重新加载数据
      }).catch(error => {
        this.$modal.msgError("操作失败: " + error.message);
      });
    }
  }
};
</script>

<!-- 进度条弹窗 -->
<el-dialog
  :visible.sync="progressVisible"
  :show-close="false"
  :close-on-click-modal="false"
  :close-on-press-escape="false"
  width="400px"
  center
>
<div style="text-align: center; padding: 20px;">
  <p style="margin-bottom: 15px; font-size: 16px;">{{ uploadStatusText }}</p>
  <el-progress
    :percentage="progressPercent"
    :format="() => `${progressPercent}%`"
    status="success"
    style="margin: 0 auto 10px;"
  />
  <p v-if="progressPercent < 100" style="color: #999; font-size: 13px;">
    数据提交中，请勿关闭窗口
  </p>
  <p v-else style="color: #67C23A; font-size: 13px;">
    提交完成
  </p>
</div>
</el-dialog>
